from flask import Flask, render_template, request, jsonify, redirect, url_for
import json
import os

app = Flask(__name__)

DATA_FILE = 'data.json'

def load_data():
    try:
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        return []

def save_data(data):
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

@app.route('/')
def index():
    data = load_data()
    return render_template('index.html', tools=data)

@app.route('/api/tools', methods=['GET'])
def get_tools():
    data = load_data()
    return jsonify(data)

@app.route('/api/tools', methods=['POST'])
def add_tool():
    data = load_data()
    new_tool = request.json
    new_tool['id'] = len(data)
    data.append(new_tool)
    save_data(data)
    return jsonify(new_tool), 201

@app.route('/api/tools/<int:tool_id>', methods=['PUT'])
def update_tool(tool_id):
    data = load_data()
    if 0 <= tool_id < len(data):
        updated_tool = request.json
        updated_tool['id'] = tool_id
        data[tool_id] = updated_tool
        save_data(data)
        return jsonify(updated_tool)
    return jsonify({'error': 'Tool not found'}), 404

@app.route('/api/tools/<int:tool_id>', methods=['DELETE'])
def delete_tool(tool_id):
    data = load_data()
    if 0 <= tool_id < len(data):
        deleted_tool = data.pop(tool_id)
        # 重新分配ID
        for i, tool in enumerate(data):
            tool['id'] = i
        save_data(data)
        return jsonify(deleted_tool)
    return jsonify({'error': 'Tool not found'}), 404

if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0', port=5000)